#include "preHeader.h"
#include "Session/ClientPacketHandler.h"
#include "Session/MapServerSession.h"
#include "Session/MapServerMgr.h"
#include "Game/Account.h"
#include "Chat/ChatServer.h"
#include "WordFilter/WordFilter.h"
#include "GameServer.h"

int ClientPacketHandler::HandleChatMessage(Account *pAccount, INetPacket &pck)
{
	// int8        | ObjGUID | string     | int8      | uint32
	// channelType | toGuid  | strViewMsg | thingType | thingId | ...

	int8 channelType;
	ObjGUID toGuid;
	std::string_view strViewMsg;
	pck >> channelType >> toGuid >> strViewMsg;

	auto strViewArgs = pck.CastReadableStringView();
	if (strViewArgs.size() % (1 + 4) != 0) {
		return SessionHandleKill;
	}

	auto strMsg = sWordFilter.DoWordFilter(strViewMsg);
	auto pChar = pAccount->GetCharacter();
	if (strViewArgs.empty()) {
		return sChatServer.HandleChatMessage(
			ChannelType(channelType), pChar, toGuid, strMsg, strViewArgs);
	}

	auto pMapServer = sMapServerMgr.GetMapServer(pChar->lastInstGuid);
	if (pMapServer == NULL) {
		return SessionHandleKill;
	}

	ConstNetPacket rpcReqPck(
		G2M_GET_CHAT_MESSAGE_THING, strViewArgs.data(), strViewArgs.size());
	pMapServer->GetSession()->RPCInvoke(rpcReqPck,
		[=, strMsg = std::move(strMsg)](INetStream& pck, int32 err, bool) {
		if (err == RPCErrorNone) {
			std::string_view strViewArgs = pck.CastReadableStringView();
			sChatServer.HandleChatMessage(
				ChannelType(channelType), pChar, toGuid, strMsg, strViewArgs);
		}
	}, &sGameServer, DEF_S2S_RPC_TIMEOUT);

	return SessionHandleSuccess;
}
